__author__ = '荣耀燃尽  世界尽头'
import pymysql
class MysqlClass:
    '''
    将数据库操作封装成类
    '''

#构造函数实现数据集库连接
    def __init__(self,sql_name,tablename):
        try:
            self.dbname=sql_name
            self.tablename=tablename
            self.db=pymysql.connect(host="localhost",user="root",password="",db=sql_name,charset="utf8")
            self.cursor=self.db.cursor()
            print("数据库连接成功！！")
        except Exception as err:
            print("错误原因：",err)
#析构函数关闭数据连接
    def __del__(self):
        self.db.close()
        print("已经关闭数据连接！！")
#find All 查询方法
    def findAll(self):
        try:
            self.cursor.execute("select * from %s"%(self.tablename))
            data=self.cursor.fetchall()
           # print("成功操作条数：",self.cursor.rowcount)
           # for vo in data:
            #    print(vo)
            return data
        except Exception as err:
            print("SQl查询错误原因：",err)

#del 通过id来删除信息
    def delstu(self,id):
        sql = "delete from %s where sid=%d"%(self.tablename,id)
        sql_set_id="alter table %s auto_increment=1"%(self.tablename)
        print(sql)
        try:
            self.cursor.execute(sql)
            self.cursor.execute(sql_set_id)
            self.db.commit()
        except Exception as err:
            self.db.rollback()
            print("SQL删除执行错误，原因：",err)

#insert添加
    def insert(self,stu):
        sql="insert into %s (name,age,classid) values('%s',%d,'%s')"%(self.tablename,stu[0],stu[1],stu[2])
        #print(sql)
        try:
            self.cursor.execute(sql);
            #print("成功操作条数：",self.cursor.rowcount)
            self.db.commit()
        except Exception as err:
            self.db.rollback()
            print("SQL添加执行错误，原因：",err)

